package com.liwen.service.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author: li.rui
 * @time: 2018-03-16 10:00
 * @description: 文件工具类
 */
public class FileUtil {

    private static Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 保存到本地文件
     * 跳过文件夹;不覆盖已存在的文件
     *
     * @param bytes     文件内容
     * @param localPath 本地路径
     */
    public static void saveFile(byte[] bytes, String localPath) {
        File file = new File(localPath);
        if (file.exists())
            return;
        if (file.isDirectory())
            return;
        String dir = localPath.substring(0, localPath.lastIndexOf("/"));
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        try {
            OutputStream os = new FileOutputStream(file);
            os.write(bytes);
            os.close();
        } catch (IOException e) {
            log.error("saveFile=localPath:{},msg:{}", localPath,e);
        }
    }


    public static byte[] FileToByte(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 文件拷贝
     */
    public static void copy(InputStream is, OutputStream os) throws IOException {
        int i;
        byte[] b = new byte[1024];
        try {
            while ((i = is.read(b)) != -1) {
                os.write(b, 0, i);
            }
        } catch (IOException e) {
            throw e;
        }
    }

//    public static void main(String[] args) {
//
//        saveFile(FileToByte(
//                new File("/Users/gulei/Downloads/hah.txt")), "/Users/gulei/Downloads/document");
//    }
}
